package controller

import "api/app/auth/auto/v1/api"
import "api/app/auth/models"
import "gitee.com/dreamwood/ez"
import "gitee.com/dreamwood/ez/server"

type ApiController struct {
	api.ApiApi
}

func init() {

	c := &ApiController{}
	c.Prepare()
	c.AddRoute("/save", c.SaveAction)
	c.AddRoute("/list", c.ListAction)
	c.AddRoute("/get", c.GetAction)
	c.AddRoute("/scan", c.ScanAction)
	c.AddRoute("/delete", c.DeleteAction)
	c.AddRoute("/delete_many", c.DeleteManyAction)
	c.AddRoute(`/edit_many`, c.SaveManyAction)
	c.AddRoute(`/tree`, c.Tree)
}

//如果不满意自动生成的方法，请自定义，本文件不会被生成器覆盖，请放心操作
//func (this *ApiController) SaveAction(operation *server.Operation) {}
//func (this *ApiController) GetAction(operation *server.Operation) {}
//func (this *ApiController) ScanAction(operation *server.Operation) {}
//func (this *ApiController) ListAction(operation *server.Operation) {}
//func (this *ApiController) DeleteAction(operation *server.Operation) {}

func (this *ApiController) Tree(operation *server.Operation) {
	root := operation.Get("root").IsInt(0)
	op := this.TakeOver(operation)
	crud := models.NewApiCrud()
	condition := ez.M{}
	if root != 0 {
		rootModel, e := crud.Find(root)
		if op.CheckError(e) {
			return
		}
		condition = ez.M{"l__gt": rootModel.L, "r__lt": rootModel.R}
	}
	full, e := crud.FindBy(condition, []string{"l"}, 0, 0)
	if op.CheckError(e) {
		return
	}
	data := this.createTree(root, full)
	op.ReturnSuccess("OK", data)
}

func (this *ApiController) createTree(root int, full []*models.Api) []map[string]interface{} {
	// 获取第一层Root
	finds := make([]*models.Api, 0)
	for _, md := range full {
		if md.ParentId == root {
			finds = append(finds, md)
		}
	}
	re := make([]map[string]interface{}, 0)
	for _, find := range finds {
		cur := make(map[string]interface{})
		// 分类树所需数据结构
		cur["id"] = find.Id
		cur["title"] = find.Name
		// 级联选择器所需数据结构
		cur["value"] = find.Id
		cur["label"] = find.Name
		cur["children"] = this.createTree(find.Id, full)
		re = append(re, cur)
	}
	return re
}

func UpdateLeftRight(operation *server.Operation) {
	models.ApiTreeModel{}.UpdateLeftAndRight(0, 0, 0)
}
